package com.wanpinghui.supplier.business;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.message.MessageP2PActivity;
import com.wanpinghui.supplier.message.PhotoBrowseActivity;
import com.wanpinghui.supplier.widgets.CustomVideoView;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.cameralibrary.util.FileUtil;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.business.bean.ContentImg;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.wanpinghui.wphlibrary.model.business.bean.SaveDynamic;
import com.wanpinghui.wphlibrary.photovideo.bean.BaseUrlBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.photovideo.interfaces.OnActionListener;
import com.wanpinghui.wphlibrary.photovideo.view.ProductImageUploadView;
import com.yunshl.yunshllibrary.storage.ShareDataManager;
import com.yunshl.yunshllibrary.storage.SharedPreferencesKey;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlEditText;
import com.yunshl.yunshllibrary.view.YunShlPopupWinow;

import org.xutils.view.annotation.ContentView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorFragment;
import me.nereo.multi_image_selector.PhotoPickManager;
import retrofit.callback.YRequestCallback;

/**
 * Created by tg596 on 2018/1/26.
 */
@ContentView(R.layout.layout_activity_release_dynamic)
public class ReleaseDynamicActivity extends BaseActivity {


    private static final int REQUEST_SELECT_PHOTO = 0x11;  //图片
    private static final int  REQUEST_SELECT_VIDEO = 0x12; // 视频
    private static final int  REQUEST_DELETE_VIDEO = 0x16; // 删除视频
    private static final int  REQUEST_SELECT_RESULT= 0x15; // 谁可以看
    private ArrayList<UploadFileBean> mImageList;//图片

    private YunShlPopupWinow popupWinow;
    /**
     * 取消
     */
    private TextView mTvCancel;
    /**
     * 发表
     */
    private TextView mTvRelease;
    /**
     * 想对行业的人说些什么
     */
    private YunShlEditText mEdtContent;
    private ProductImageUploadView mPiuvRemarkImage;
    private CustomVideoView video_view;
    private RelativeLayout rl_video;
    private FrameLayout mFlWhoCanSee;
    private TextView mTvWhoCanSee;
    private View view;
    private String video_path;
    private int visible_type  = 1;
    private String area_ids;
    private String path;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        mTvCancel = (TextView) findViewById(R.id.tv_cancel);
        mTvRelease = (TextView) findViewById(R.id.tv_release);
        mEdtContent = (YunShlEditText) findViewById(R.id.edt_content);
        mPiuvRemarkImage = (ProductImageUploadView) findViewById(R.id.piuv_remark_image);
        mFlWhoCanSee = (FrameLayout) findViewById(R.id.fl_who_can_see);
        video_view = (CustomVideoView)findViewById(R.id.video_view);
        rl_video = (RelativeLayout)findViewById(R.id.rl_video);
        mTvWhoCanSee= (TextView)findViewById(R.id.tv_whocansee);
    }

    @Override
    public void bindEvents() {
        mPiuvRemarkImage.setOnActionListener(new OnActionListener() {
            @Override
            public void onItemDelete(int position) {
                if (mPiuvRemarkImage.getMaxCount() == 1){
                    FileUtil.deleteFile(video_path);
                }
                mImageList.remove(position);
                mPiuvRemarkImage.setData(mImageList);
            }

            @Override
            public void onItemClick(int position) {
                if (UploadFileBean.haveVideo(mImageList)){
//                    FileInputStream fis = null;
//                    try {
//                        fis = new FileInputStream(mImageList.get(position).getForderPath());
//                        Bitmap bitmap  = BitmapFactory.decodeStream(fis);
//                        VideoPlayActivity.startWithElement(ReleaseDynamicActivity.this,mImageList.get(position).getPath(),mPiuvRemarkImage,bitmap);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
                    Intent intent = new Intent(ReleaseDynamicActivity.this,VideoPreviewActivity.class);
                    intent.putExtra("path",mImageList.get(position).getPath());
                    startActivityForResult(intent,REQUEST_DELETE_VIDEO);
                }else {
                    if (mImageList != null && mImageList.size() > 0) {
                        ArrayList<String> strings = new ArrayList<>();
                        for (UploadFileBean img : mImageList) {
                            strings.add(img.getPath());
                        }
                        PhotoBrowseActivity.startWithElement1(ReleaseDynamicActivity.this, strings, position, view, null);
                    }
                }
            }

            @Override
            public void onAddMoreClick() {
                showDialog();

           //     PhotoPickManager.selectPicNoCamera(ReleaseDynamicActivity.this, REQUEST_SELECT_PHOTO, 9, false, mImageList == null ? 0 : mImageList.size());
            }




            @Override
            public void onItemPositionChange() {

            }
        });
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtil.deleteFile(video_path);
                finish();
            }
        });
        mFlWhoCanSee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(ReleaseDynamicActivity.this,WhoCanSeeActivity.class),REQUEST_SELECT_RESULT);
            }
        });
        video_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
               // ToastManager.getInstance().showToast("111");

                Intent intent = new Intent(ReleaseDynamicActivity.this,VideoPreviewActivity.class);
                intent.putExtra("path",video_path);
                //   startActivityForResult(intent,REQUEST_DELETE_VIDEO);
                ActivityOptionsCompat compat = null;
                if (video_view == null) {
                    compat = ActivityOptionsCompat.makeSceneTransitionAnimation(ReleaseDynamicActivity.this);
                } else {
                    compat = ActivityOptionsCompat.makeSceneTransitionAnimation(ReleaseDynamicActivity.this, video_view,
                            "tansition_view");
                }
                ActivityCompat.startActivity(ReleaseDynamicActivity.this, intent, compat.toBundle());

                return false;
            }
        });
        mTvRelease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (mImageList != null && mImageList.size()>0){
                    if (mPiuvRemarkImage.getMaxCount() == 1){
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(path, options);
                        int w = options.outWidth;
                        int h = options.outHeight;
                        mImageList.add(new UploadFileBean(1,path,h,w));
                    }
                    LoadingDialog.Build(ReleaseDynamicActivity.this).setContent("正在发布").show();
                    WPHSdk.getService(BusinessService.class)
                            .uploadPictures(mImageList, new YRequestCallback<List<BaseUrlBean>>() {
                                @Override
                                public void onSuccess(List<BaseUrlBean> var1) {

                                    SaveDynamic bean = new SaveDynamic();
                                    try {
                                        bean.setContent(URLEncoder.encode(mEdtContent.getTextString(),"UTF-8"));
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                    if (visible_type ==21 || visible_type == 31 ){

                                        bean.setArea_ids(area_ids);
                                    }
                                    bean.setVisible_type(visible_type);
                                    if (mPiuvRemarkImage.getMaxCount() == 1) {
                                        BaseUrlBean videoBean = null;
                                        String thumd_url = null;
                                        int wight = 0;
                                        int height = 0;
                                        for (int i = 0; i < var1.size(); i++) {
                                            if (var1.get(i).getUrl().contains(".mp4")) {
                                                videoBean = var1.get(i);
                                            } else {
                                                thumd_url = var1.get(i).getUrl();
                                                wight = var1.get(i).getWidth();
                                                height = var1.get(i).getHeight();
                                            }
                                        }

                                        if (videoBean != null) {
                                            videoBean.setThumb_url(thumd_url);
                                            videoBean.setHeight(height);
                                            videoBean.setWidth(wight);
                                            var1.clear();
                                            var1.add(videoBean);
                                        }
                                    }
                                    bean.setPictures(new Gson().toJson(var1));
                                    saveDynamic(bean);
                                }

                                @Override
                                public void onFailed(int var1, String message) {
                                    LoadingDialog.dismissDialog();
                                }

                                @Override
                                public void onException(Throwable var1) {
                                    LoadingDialog.dismissDialog();
                                }
                            });
                }else {
                    if (TextUtil.isNotEmpty(mEdtContent.getTextString())) {
                        SaveDynamic bean = new SaveDynamic();
                        bean.setContent(mEdtContent.getTextString());
                        if (visible_type ==21 || visible_type == 31 ){
                            bean.setArea_ids(area_ids);
                        }


                        bean.setVisible_type(visible_type);
                        saveDynamic(bean);
                    }
                }
            }
        });

    }

    public  void  saveDynamic(SaveDynamic dynamic){

        WPHSdk.getService(BusinessService.class)
                .saveDynamic(dynamic, new YRequestCallback<Object>() {
                    @Override
                    public void onSuccess(Object var1) {
                        LoadingDialog.dismissDialog();
                        ToastManager.getInstance().showToast("发布成功");
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        LoadingDialog.dismissDialog();
                        showWarningText(message);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        LoadingDialog.dismissDialog();
                    }
                });
    }

    private void showDialog() {

        if (popupWinow == null) {
            view = LayoutInflater.from(this).inflate(R.layout.view_shoot_photo, null);
            popupWinow = new YunShlPopupWinow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWinow.dismiss();
                }
            });
            view.findViewById(R.id.tv_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWinow.dismiss();
                    PhotoPickManager.selectPicNoCamera(ReleaseDynamicActivity.this, REQUEST_SELECT_PHOTO, 9, false, mImageList == null ? 0 : mImageList.size());
                }
            });

            view.findViewById(R.id.ll_shoot).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWinow.dismiss();
                    if (ContextCompat.checkSelfPermission(ReleaseDynamicActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {

                                requestPermissions(new String[]{Manifest.permission.CAMERA}, MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);

                            } else {

                                requestPermissions(new String[]{Manifest.permission.CAMERA}, MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);

                            }
                        }
                    } else {
                        Intent intent = new Intent(ReleaseDynamicActivity.this,CameraActivity.class);
                        if (mImageList != null && mImageList.size()>0) {
                            if (!UploadFileBean.haveVideo(mImageList)) {
                                intent.putExtra("onlyPhoto", true);
                            } else {
                                intent.putExtra("onlyPhoto", false);
                            }
                        }else {
                            intent.putExtra("onlyPhoto", false);
                        }
                        startActivityForResult(intent,REQUEST_SELECT_VIDEO);
                    }


                }
            });
        }
        popupWinow.setCommonConfig(this, YunShlPopupWinow.AnimaDirect.DIRECT_BOTTOM_TOP);
        popupWinow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(ReleaseDynamicActivity.this,CameraActivity.class);
                if (mImageList != null && mImageList.size()>0) {
                    if (!UploadFileBean.haveVideo(mImageList)) {
                        intent.putExtra("onlyPhoto", true);
                    } else {
                        intent.putExtra("onlyPhoto", false);
                    }
                }else {
                    intent.putExtra("onlyPhoto", false);
                }
                startActivityForResult(intent,REQUEST_SELECT_VIDEO);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void initData() {
        mImageList = new ArrayList<>();
        ArrayList list = getIntent().getStringArrayListExtra("data");
        if (list != null && list.size()>0) {
            mImageList.addAll(UploadFileBean.create(list));
            if (mImageList.size() > 0) {
                mPiuvRemarkImage.setData(mImageList);
            }
        }
        UploadFileBean bean = getIntent().getParcelableExtra("bean");
        if (bean!= null){
            mImageList.add(bean);
            mPiuvRemarkImage.setData(mImageList);
            mPiuvRemarkImage.setMaxCount(1);
              mPiuvRemarkImage.setSubmit(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareDataManager.getInstance().delete(this, SharedPreferencesKey.SELECT_WHO_CAN_SEE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_SELECT_PHOTO:
                if (data != null && resultCode == RESULT_OK) {
//                    Intent intent = new Intent(ReleaseDynamicActivity.this, ReleaseDynamicActivity.class);
//                    intent.putExtra("data", PhotoPickManager.getPhoto(data));
//                    startActivityForResult(intent, CLIP_PHOTO);
                    mImageList.addAll(UploadFileBean.create(PhotoPickManager.getPhoto(data)));
                    mPiuvRemarkImage.setData(mImageList);
                }
                break;
            case REQUEST_SELECT_VIDEO:
                if (data!= null) {

                     path = data.getStringExtra("img_bitmap_url");
                     video_path = data.getStringExtra("url");
                    if (TextUtil.isNotEmpty(video_path) && TextUtil.isNotEmpty(path) ) {

//                        rl_video.setVisibility(View.VISIBLE);
//                        mPiuvRemarkImage.setVisibility(View.GONE);
//                        video_view.setVideoPath(video_path);
//                        video_view.start();
//                        video_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//
//                            @Override
//                            public void onPrepared(MediaPlayer mp) {
//                                mp.setVolume(0f,0f);
////                                mp.start();
////                                mp.setLooping(true);
//
//                            }
//                        });
//
//                        video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                            @Override
//                            public void onCompletion(MediaPlayer mp) {
//                                mp.setVolume(0f,0f);
//                                video_view.setVideoPath(video_path);
//                                video_view.start();
//
//                            }
//                        });

                        UploadFileBean bean = new UploadFileBean(2,video_path);
                        bean.setForderPath(path);
                        bean.setFinishDelete(true);
                        mImageList.add(bean);
                        mPiuvRemarkImage.setMaxCount(1);
                        mPiuvRemarkImage.setData(mImageList);




//                        mPiuvRemarkImage.setSubmit(true);

                    }else if (TextUtil.isNotEmpty(path)) {
                        rl_video.setVisibility(View.GONE);
                        mPiuvRemarkImage.setMaxCount(9);
                        mPiuvRemarkImage.setSubmit(false);
                        ArrayList<String> arrayList = new ArrayList<>();
                        arrayList.add(path);
                        if (arrayList != null && arrayList.size()>0) {
                            mImageList.addAll(UploadFileBean.create(arrayList));
                            if (mImageList.size() > 0) {
                                mPiuvRemarkImage.setData(mImageList);
                            }
                        }
                    }

                }
                break;
            case REQUEST_DELETE_VIDEO:
                if (resultCode == REQUEST_DELETE_VIDEO){
                    mImageList.clear();
                    mPiuvRemarkImage.setData(mImageList);
                }
                break;
            case REQUEST_SELECT_RESULT :
                if (data != null  ){
                    String name = data.getStringExtra("data");
                    visible_type =data.getIntExtra("visible_type",1);
                    area_ids = data.getStringExtra("area_ids");
                    if (TextUtil.isNotEmpty(name)){
                        mTvWhoCanSee.setText(name);
                    }

                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        FileUtil.deleteFile(video_path);
    }
}
